package com.xayq.orap.oauth.controller;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.ParameterStyle;
import org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest;
import org.apache.oltu.oauth2.rs.response.OAuthRSResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xayq.orap.service.OAuthService;


@Controller
public class ResourceRequestController {

	@Autowired
	OAuthService oAuthService;
	
	@RequestMapping("/check-token")
	public void checkAccessToken(HttpServletRequest request, HttpServletResponse response) throws OAuthSystemException{
		try {

//            //构建OAuth资源请求
//            OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest(request);
//            //获取Access Token
//            String accessToken = oauthRequest.getAccessToken();

            //验证Access Token
//            if (!oAuthService.checkAccessToken(request)) {
//                // 如果不存在/过期了，返回未验证错误，需重新验证
//                OAuthResponse oauthResponse = OAuthRSResponse
//                        .errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
//                        .setRealm("Apache Oltu")
//                        .setError(OAuthError.ResourceResponse.INVALID_TOKEN)
//                        .buildHeaderMessage();
//
//                HttpHeaders headers = new HttpHeaders();
//                headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
//                return new ResponseEntity(headers, HttpStatus.UNAUTHORIZED);
//            }
//            //返回用户名
//            String username = oAuthService.getUsernameByAccessToken(accessToken);
//            return new ResponseEntity(username, HttpStatus.OK);
            if(oAuthService.checkAccessToken(request,response)){
	            response.setHeader("Access-Control-Allow-Origin", "*");
	            response.setContentType("application/json; charset=utf-8");    //json
	            response.setStatus(HttpServletResponse.SC_OK);
	            PrintWriter out = response.getWriter();
	            out.print("Resource request Valid");
	            out.flush();
            }
        } catch (Exception e) {
            //检查是否设置了错误码
            e.printStackTrace();
        }
	}
}
